﻿using Microsoft.AspNetCore.Http;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WCS_Service.DomianService.Interface;
using WCS_Utility.ConstString;

namespace WCS_Service.DomianService.ComDomainService
{
    /// <summary>
    /// Http通信服务
    /// </summary>
    public class HttpComDomainService : IHttpComDomainService , IDisposable
    {


        private readonly HttpClient _httpClient;

        public HttpComDomainService()
        {
            _httpClient = new HttpClient();
            _httpClient.Timeout = TimeSpan.FromSeconds(30);
        }

        public async Task<string> GetAsync(string url)
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                return responseBody;
            }
            catch (HttpRequestException e)
            {
                Log.Error($"GET请求失败: {e.Message}");
                return null;
            }
        }

        public async Task<string> PostAsync(string url, string jsonPayload)
        {
            try
            {
                HttpContent content = new StringContent(jsonPayload, Encoding.UTF8, ConstStringData.MediaType);
                HttpResponseMessage response = await _httpClient.PostAsync(url, content);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                return responseBody;
            }
            catch (HttpRequestException e)
            {
                Log.Error($"POST请求失败: {e.Message}");
                return null;
            }
        }

        public void Dispose()
        {
            _httpClient.Dispose();
        }
    }
}
